package com.aqie.easy.bitOperation;

/**
 * 191 位1的个数
 */
public class HammingWeight {
    /**
     * api + 循环
     * @param n
     * @return
     */
    public int hammingWeight(int n) {
        int ans = 0;
        String s = Integer.toBinaryString(n);
        for (int i = 0; i < s.length(); ++i){
            if (s.charAt(i) == '1') ans++;
        }
        return ans;
    }

    /**
     * 掩码 + 位移
     * @param n
     * @return
     */
    public int hammingWeight2(int n) {
        int ans = 0;
        int mask = 1;
        for (int i = 0; i< 32; i++){
            if ((n & mask) != 0){
                ans++;
            }
            mask <<= 1;
        }
        return ans;
    }

    // todo
    public int hammingWeight3(int n) {
        int sum = 0;
        while (n != 0) {
            sum++;
            n &= (n - 1);
        }
        return sum;
    }

    public static void main(String[] args) {
        int n = -3;
        System.out.println(Integer.toBinaryString(n));
    }
}
